import os
from ftplib import FTP
import sys
import ConfigParser
import argparse
import copy

parser = argparse.ArgumentParser(description='up/down/add files through ftp')
parser.add_argument('operate',metavar = 'operator',help="[up | down | rm(rmd) |del(delete)]")
parser.add_argument('filename',metavar='filename',help='the path of the fiel to operate')
args = parser.parse_args()

cf = ConfigParser.ConfigParser()
cf.read("aud.conf")    
username = cf.get("remote","username")
password = cf.get("remote","password")
host = cf.get("remote","host")
remote_dir = cf.get("remote","dir")
bufs = 1024

try:
    bufs = cf.getint("local","bufsize")
except:
    pass

ftp = FTP(host)
ftp.login(username,password)
ftp.cwd(remote_dir)

def up(filename,ftp,bufs=1024):
    if not os.path.exists(filename):
        print "file ["+filename + "] does not exist"
        return
    try:
        f = open(filename,"r")
        print ftp.storbinary("STOR %s" % filename,f,bufs)
        f.close()
    except Exception,e:
        print e

    
def down(filename,ftp,bufs=1024):
    if os.path.isdir(filename):
        print "error: [%s] is a directory,which should be a file"%filename
        return
    try:
        print ftp.retrbinary('RETR %s'%filename,open(filename,"wb").write,bufs)
    except Exception,e:
        print e

def delete(filename,ftp,bufs = 1024):
    print "start to del file %s ..." % filename
    try:
        print ftp.delete(filename)
    except Exception,e:
        print e
def rmd(filename,ftp,bufs=1024):
    try:
        print ftp.rmd(filename)
    except Exception,e:
        print e
        
def _cp_conf(dirname,cf = cf):
    new_path = os.path.join(cf.get("remote","dir"),dirname)
    cf.set("remote","dir",new_path)
    with open(dirname+"/aud.conf","w") as fi:
        cf.write(fi)

def mkdir(filename,ftp,bufs = 1024):
    try:
        print ftp.mkd(filename)
    except Exception,e:
        print e
    if not os.path.exists(filename):
        os.mkdir(filename)
    if os.path.isfile(filename):
        print "error:exists a file whose name is [%s]"
        return
    else:
        _cp_conf(filename)
            

opdict = { "up": up,
           "down":down,
           "del":delete,
           "delete":delete,
           "rmd":rmd,
           "rm":rmd,
           "mkdir":mkdir
           }

try:
    opdict[args.operate](args.filename,ftp,bufs)
except Exception,e:
    print "operate %s not found"%args.operate,e

ftp.quit()
